package best.driver.android.Utils;

import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import best.driver.android.AppConfig;
import best.driver.android.AppInfo;
import best.driver.android.Beans.FileInfo;
import best.driver.android.BestApp;
import best.driver.android.Event.UploadFileEvent;
import best.driver.android.manager.UserInfoManager;
import com.google.gson.Gson;
import de.greenrobot.event.EventBus;
import org.json.JSONObject;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class FileImageUpload {
    public static final String FILE_PATH = "/crop.jpg";
    public static final String FILE_PATH_CAR = "/crop_car.jpg";
    public static final String FILE_PATH_DRIVING_LICENCE = "/crop_driving_licence";
    //public static final String FILE_PATH_
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 10000000; //超时时间
    private static final String CHARSET = "utf-8"; //设置编码
    public static final String SUCCESS = "1";
    public static final String FAILURE = "0";

    /**
     * android上传文件到服务器
     *
     * @param file       需要上传的文件
     * @param RequestURL 请求的rul
     * @return 返回响应的内容
     */
    public static String uploadFile(File file, String RequestURL,final int type, FileInfo fileInfo) {
        String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; //内容类型
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true); //允许输入流
            conn.setDoOutput(true); //允许输出流
            conn.setUseCaches(false); //不允许使用缓存
            conn.setRequestMethod("POST"); //请求方式
            conn.setRequestProperty("Charset", CHARSET);
            conn.setRequestProperty("useragent", AppConfig.APP_VERSION +";"+ Build.MODEL + ";Android/" +Build.VERSION.RELEASE +";"+ "WIFI;" + PhoneFunc.getImei());
            conn.setRequestProperty("access-token", UserInfoManager.getInstance().getToken());
            //设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            if (file != null) {
                /** * 当文件不为空，把文件包装并且上传 */
                OutputStream outputSteam = conn.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();

                String[] props = { "file", "appId","appKey", "version",
                        "deviceId", "deviceName", "os","avatar"};
                String[] values = {"file",
                        "RYJ-MOBILE-ANDROID","1474e604a5824c68beadec64707003de","1.0","13","asdfsf",
                        "Android", file.getName()};

                for (int i = 0; i < props.length; i++) { // send each property
                    sb = sb.append(PREFIX);
                    sb = sb.append(BOUNDARY);
                    sb = sb.append(LINE_END);
                    sb = sb.append("Content-Disposition: form-data; name=\""
                            + props[i] + "\"\r\n\r\n");
                    sb = sb.append(values[i]);
                    sb = sb.append(LINE_END);
                }

                /**
                 * 这里重点注意：
                 * name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字，包含后缀名的 比如:abc.png
                 */
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: image/png"  + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功
                 * 当响应成功，获取响应的流
                 */
                final int res = conn.getResponseCode();
                Log.e(TAG, "response code:" + res);
                InputStream in = conn.getInputStream();
                String result = "";
                try {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    int length;
                    byte[] buffer = new byte[512];
                    while ((length = in.read(buffer)) != -1) {
                        out.write(buffer, 0, length);
                    }
                    String outString = new String(out.toByteArray());
                    if(!TextUtils.isEmpty(outString)) {
                        try {
                            JSONObject object = new JSONObject(outString);
                            result =  object.optString("result", "");
                            final String temp = result;
                            Logger.d("pic_id", result);
//                            BestApp.getInstance().getLastActivity().runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    AppInfo.showToast(BestApp.getInstance(), temp);
//                                }
//                            });

                            fileInfo.mFileId = new String(result);
                            final UploadFileEvent event = new UploadFileEvent();
                            event.mFileId = result;
                            BestApp.handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    EventBus.getDefault().post(event);
                                }
                            }, 100);

                            if(type == 0) {
                                UserInfoManager.getInstance().setIdentifyFrontId(result);
                            } else if (type == 1) {
                                UserInfoManager.getInstance().setIdentifyBackId(result);
                            } else if (type == 2) {
                                UserInfoManager.getInstance().setCarPicId(result);
                            } else if (type == 3) {
                                UserInfoManager.getInstance().setDrivingCarPicId(result);
                            } else if (type == 4) {
                                UserInfoManager.getInstance().setOnRoadPicId(result);
                            } else if (type == 5) {
                                UserInfoManager.getInstance().setOperationPicId(result);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } finally {
                    in.close();
                }
                if (res == 200 && !TextUtils.isEmpty(result)) {
                    BestApp.getInstance().getLastActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            String hint = "";
                            if (type == 0) {
                                hint = "身份证正面上传成功";
                            } else if (type == 1) {
                                hint = "身份证背面上传成功";
                            } else if (type == 2) {
                                hint = "车辆照片上传成功";
                            } else if (type == 3) {
                                hint = "驾驶证照片上传成功";
                            } else if (type == 4) {
                                hint = "行驶证照片上传成功";
                            } else if (type == 5) {
                                hint = "营运证照片上传成功";
                            }
                            if(!TextUtils.isEmpty(hint))
                            Toast.makeText(BestApp.getInstance().getApplicationContext(), hint, Toast.LENGTH_SHORT).show();

                        }
                    });
                    return SUCCESS;
                } else {
                    BestApp.getInstance().getLastActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            String hint = "";
                            if (type == 0) {
                                hint = "身份证正面上传失败: ";
                            } else if (type == 1) {
                                hint = "身份证背面上传失败: ";
                            } else if (type == 2) {
                                hint = "车辆照片上传失败: ";
                            } else if (type == 3) {
                                hint = "驾驶证照片上传失败: ";
                            } else if (type == 4) {
                                hint = "行驶证照片上传失败: ";
                            } else if (type == 5) {
                                hint = "营运证照照上传失败: ";
                            } else if (type == 6 || type == 7) {
                                hint = "照片上传失败";
                            }
                            Toast.makeText(BestApp.getInstance().getApplicationContext(), hint, Toast.LENGTH_SHORT).show();

                        }
                    });
                }
            }
        } catch (final MalformedURLException e) {

            BestApp.getInstance().getLastActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    e.printStackTrace();
                    Toast.makeText(BestApp.getInstance().getApplicationContext(), "网络出现异常，请重新上传", Toast.LENGTH_LONG).show();
                }
            });

        } catch (final IOException e) {
            BestApp.getInstance().getLastActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    e.printStackTrace();
                    Toast.makeText(BestApp.getInstance().getApplicationContext(), "网络出现异常，请重新上传", Toast.LENGTH_LONG).show();
                }
            });

        }
        return FAILURE;
    }

    private Map<String, String> getHeaderParam(){
        HashMap<String, String> headerMap = new HashMap<String, String>();
        headerMap.put("useragent", "V1.0;Apple iPhone 6;iOS/8.4;WIFI;0ccc1230");
        headerMap.put("Content-Type", "application/json");
        headerMap.put("access-token", UserInfoManager.getInstance().getToken());
        return headerMap;
    }

    public static boolean saveBitmap2file(Bitmap bmp)

    {
        Bitmap.CompressFormat format = Bitmap.CompressFormat.PNG;

        int quality = 100;

        OutputStream stream = null;

        try

        {

            // 判断SDcard状态

            if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))

            {

                // 错误提示

                return false;

            }


            // 检查SDcard空间

            File SDCardRoot = Environment.getExternalStorageDirectory();

            if (SDCardRoot.getFreeSpace() < 10000)

            {

                // 弹出对话框提示用户空间不够

                Log.e("Utils", "存储空间不够");

                return false;

            }


            // 在SDcard创建文件夹及文件

            File bitmapFile = new File(SDCardRoot.getPath() + FILE_PATH);

            bitmapFile.getParentFile().mkdirs(); // 创建文件夹
            if(!bitmapFile.exists())
                bitmapFile.createNewFile();

            stream = new FileOutputStream(SDCardRoot.getPath() + FILE_PATH); // "/sdcard/"

        } catch (Exception e)

        {
            Toast.makeText(BestApp.getInstance().getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
            e.printStackTrace();

        }

        return bmp.compress(format, quality, stream);

    }
}

